import { DataTypes } from "sequelize";

export default (sequelize) => {
  const FileChunk = sequelize.define(
    "FileChunk",
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        defaultValue: DataTypes.UUIDV4,
        comment: "分片唯一ID",
      },
      file_hash: {
        type: DataTypes.STRING,
        allowNull: true, // 这个字段不能为null
        comment: "文件哈希",
      },
      upload_id: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "上传会话ID",
      },
      chunk_index: {
        type: DataTypes.INTEGER,
        allowNull: false,
        comment: "分片索引",
      },
      chunk_path: {
        type: DataTypes.STRING(512),
        allowNull: false,
        comment: "分片存储路径",
      },
      chunk_size: {
        type: DataTypes.BIGINT,
        allowNull: false,
        comment: "分片大小",
      },
      chunk_hash: {
        type: DataTypes.STRING(64),
        allowNull: true,
        comment: "分片哈希值",
      },
      status: {
        type: DataTypes.ENUM("pending", "uploaded", "verified", "failed"),
        defaultValue: "uploaded",
        comment: "分片状态",
      },
    },
    {
      tableName: "file_chunks",
      timestamps: true,
      indexes: [
        { fields: ["upload_id"] },
        { fields: ["chunk_index"] },
        { fields: ["status"] },
        { fields: ["upload_id", "chunk_index"], unique: true }, // 唯一约束
      ],
    }
  );

  // 关联分类
  FileChunk.associate = (models) => {
    FileChunk.belongsTo(models.File, {
      foreignKey: "file_id",
      as: "file",
    });

  }


  return FileChunk;
};
